<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
  import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
  import * as echarts from 'echarts/core';
  import { BarChart } from 'echarts/charts';
  import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    DatasetComponent,
    TransformComponent
  } from 'echarts/components';
  import { LabelLayout, UniversalTransition } from 'echarts/features';
  import { CanvasRenderer } from 'echarts/renderers';

  // 注册必须的组件
  echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    DatasetComponent,
    TransformComponent,
    BarChart,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer
  ]);

  const props = defineProps({
    chartData: {
      type: Array,
      default: () => []
    },
    chartOptions: {
      type: Object,
      default: () => ({})
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    }
  });

  const chartRef = ref(null);
  let chartInstance = null;

  // 初始化图表
  const initChart = () => {
    if (!chartRef.value) return;

    // 销毁旧实例
    if (chartInstance) {
      chartInstance.dispose();
    }

    // 创建新实例
    chartInstance = echarts.init(chartRef.value);

    // 设置图表配置
    const mergedOptions = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['计划', '正常完成', '超期完成']
      },
      toolbox: {
        show: true,
        feature: {
          dataView: { show: true, readOnly: false },
          magicType: { show: true, type: ['line', 'bar'] },
          restore: { show: true },
          saveAsImage: { show: true }
        }
      },
      calculable: true,
      xAxis: [
        {
          type: 'category',
          // prettier-ignore
          data: [],
          name: '部门'
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '数量'
        }
      ],
      series: [
        {
          name: '计划',
          type: 'bar',
          data: [100, 5],
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              { type: 'min', name: 'Min' }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }]
          }
        },
        {
          name: '正常完成',
          type: 'bar',
          data: [100, 5],
          markPoint: {
            data: [
              { name: 'Max', value: 182.2, xAxis: 7, yAxis: 183 },
              { name: 'Min', value: 2.3, xAxis: 11, yAxis: 3 }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }]
          }
        },
        {
          name: '超期完成',
          type: 'bar',
          data: [100, 5],
          markPoint: {
            data: [
              { name: 'Max', value: 182.2, xAxis: 7, yAxis: 183 },
              { name: 'Min', value: 2.3, xAxis: 11, yAxis: 3 }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }]
          }
        }
      ]
    };

    chartInstance.setOption(mergedOptions);

    // 监听窗口大小变化，自适应图表
    window.addEventListener('resize', handleResize);
  };

  // 处理窗口大小变化
  const handleResize = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  // 更新图表数据
  const updateChartData = () => {
    if (!chartInstance || !props.chartData.length) return;

    // 提取x轴和y轴数据
    const xData = props.chartData.map((item) => item.name);
    const yData = props.chartData.map((item) => item.value);

    // 更新图表数据
    chartInstance.setOption({
      xAxis: {
        data: xData
      },
      series: [
        {
          data: yData
        }
      ]
    });
  };

  // 生命周期钩子
  onMounted(() => {
    initChart();
    updateChartData();
  });

  onBeforeUnmount(() => {
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
    window.removeEventListener('resize', handleResize);
  });

  // 监听props变化
  watch(
    () => [props.chartData, props.chartOptions],
    () => {
      if (chartInstance) {
        updateChartData();
      }
    },
    { deep: true }
  );
</script>

<style scoped>
  .chart-container {
    width: 100%;
    height: 700px;
  }
</style>
